<template>
  <plain-page>
    <el-container>
      <el-aside width="400px" style="box-shadow:none;margin-right: 2px">
        <el-card shadow="never" style="height: calc(100% - 2px);">
          <span slot="header">分类</span>
          <el-tree
            ref="tree"
            :data="categories"
            node-key="id"
            :props="{
              children: 'children',
              label: 'name'
            }"
            default-expand-all
            @node-click="onCategoryNodeClick"
          >
            <template v-slot="{node, data}">
            <span class="tree-node">
              <span :class="{'el-icon-folder': !data.price}">&nbsp;{{node.label}}</span>
              <span style="margin-left: 46px;">
                <el-button
                  v-if="!data.price"
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  plain
                  circle
                  @click.stop="onAddCategoryClick(data)"
                />
                <delete-confirm-button
                  v-if="data.id > 0"
                  icon
                  size="mini"
                  @ok="onDeleteClick(data)"
                />
                <empty-button v-else width="38px" />
              </span>
            </span>
            </template>
          </el-tree>
        </el-card>
      </el-aside>
      <el-card ref="listCard" shadow="never">
        <span slot="header">知识资源
          <span v-if="selectedCategory.id">（ 分类: <span style="font-style: italic;">{{selectedCategory.name}}</span> ）</span>
        </span>
        <data-table-app-view :containerSubtractHeight="117">
          <div slot="toolbar">
            <el-form inline :model="searchForm">
              <el-form-item label="资源类型">
                <type-select
                  v-model="searchForm.resourceType"
                  :items="DictMan.items('kbase.resource.type')"
                  style="width: 140px"
                />
              </el-form-item>
              <el-form-item label="标题">
                <el-input v-model="searchForm.title" clearable style="width: 100px"></el-input>
              </el-form-item>
              <el-form-item>
                <data-table-query-button :query-params="searchForm" />
                <el-dropdown
                  type="default"
                  icon="el-icon-plus"
                  trigger="hover"
                  size="medium"
                  style="margin-left: 10px"
                  @command="onResourceCommand($event)"
                >
                  <el-button>
                    <i class="el-icon-plus"></i>
                    <span>增加</span>
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="item in DictMan.items('kbase.resource.type')"
                      :key="item.value"
                      :command="item.value"
                    >
                      {{item.text}}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-form-item>
            </el-form>
          </div>
          <data-table
            ref="table"
            url="/api/kbase/resource/page"
            lazy
            style="width: 760px"
            :pagination="{pageSize: 50}"
          >
            <el-table-column prop="categoryName" label="所属分类" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="resourceTypeText" label="资源类型" width="100" ></el-table-column>
            <el-table-column prop="title" label="标题" width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createAt" label="创建时间" width="152"></el-table-column>=
            <el-table-column v-slot="{row: resource}">
              <el-popover
                v-if="resource.resourceType == 1"
                placement="bottom-start"
                width="200"
                trigger="hover"
              >
                <el-link
                  type="primary"
                  :href="`/api/kbase/resource/raw?id=${resource.id}`"
                >下载</el-link>
                <el-link
                  v-if="!['doc', 'docx', 'rar', 'zip'].includes(resource.url.substring(resource.url.lastIndexOf('.') + 1))"
                  type="primary"
                  target="_blank"
                  :href="resource.url"
                  style="margin-left: 8px;"
                >打开</el-link>
                <p>{{resource.content}}</p>
                <el-button slot="reference" type="info" plain>查看</el-button>
              </el-popover>
              <el-button v-else type="info" plain @click="onViewArticleResourceClick(resource)">查看</el-button>
              <el-button v-if="resource.resourceType == 2" @click="onEditArticleResourceClick(resource)">编辑</el-button>
              <empty-button v-else width="56px" />
              <delete-confirm-button icon @ok="onDeleteResourceClick(resource)" />
            </el-table-column>
          </data-table>
        </data-table-app-view>
      </el-card>
    </el-container>

    <add-category ref="addCategory" />
    <upload-file-dialog ref="uploadFileDialog" />
  </plain-page>
</template>

<script>
import AddCategory from './AddCategory';
import UploadFileDialog from './UploadFileDialog';

export default {
  pageProps: {
    title: '知识库'
  },
  components: {
    AddCategory,
    UploadFileDialog
  },
  data() {
    return {
      categories: [],
      searchForm: {},
      selectedCategory: {
        id: 0
      }
    }
  },
  mounted() {
    this.queryTree();
    this.$refs.table.query();
  },
  methods: {
    async queryTree() {
      this.categories = [{
        id: 0,
        name: '全部',
        children: await this.$http.get('/api/kbase/category/tree')
      }];
    },
    onCategoryNodeClick(node) {
      this.selectedCategory = node;
      this.$refs.table.query({categoryId: node.id === 0 ? '' : node.id});
    },
    onAddCategoryClick(category) {
      this.$refs.addCategory.show({
        category,
        onSuccess: () => {
          this.queryTree();
          this.$refs.table.clear();
        }
      });
    },
    async onDeleteClick(category) {
      const ret = await this.$http.delete('/api/kbase/category', {params: {id: category.id}});
      if (ret.success) {
        this.$message.success('删除成功');
        this.queryTree();
      } else {
        this.$message.error({2: '下面有子分类，不能删除'}[ret.code]);
      }
    },
    async queryResourceTable() {
      this.$refs.table.query({categoryId: this.$refs.tree.getCurrentKey()});
    },
    onResourceCommand(cmd) {
      if (!this.$refs.tree.getCurrentNode() || this.$refs.tree.getCurrentKey() == 0) {
        this.$message.warning('请先选择分类');
        return;
      }
      switch(+cmd) {
        case 1:
          this.$refs.uploadFileDialog.show({
            parentCategory: this.$refs.tree.getCurrentNode(),
            onSuccess: () => {
              this.queryResourceTable();
            }
          });
          break;
        case 2:
          this.pushPage({
            path: '/kbase/article-edit',
            params: {
              parentCategory: this.$refs.tree.getCurrentNode(),
              onSuccess: () => {
                this.queryResourceTable();
              }
            }
          });
          break;
      }
    },
    onEditArticleResourceClick(resource) {
      this.pushPage({
        key: resource.id,
        path: '/kbase/article-edit',
        subTitle: resource.title,
        params: {
          resource,
          onSuccess: () => {
            this.queryResourceTable();
          }
        }
      });
    },
    onViewArticleResourceClick(resource) {
      this.pushPage({
        key: resource.id,
        path: '/kbase/article-view',
        subTitle: resource.title,
        params: {
          resource
        }
      });
    },
    async onDeleteResourceClick(resource) {
      const ret = await this.$http.delete('/api/kbase/resource', {params: {id: resource.id}});
      if (ret.success) {
        this.$message.success('删除成功');
        this.queryResourceTable();
      }
    }
  }
}
</script>

<style scoped>
>>> .el-tree-node__content {
  height: 40px;
}
.tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.el-table__row .el-button {
  margin-left: 0px;
}
</style>